package com.miao.edu.user.controller;

import cn.hutool.core.util.PhoneUtil;
import com.miao.edu.common.UserManager;
import com.miao.edu.common.entity.ResponseDTO;
import com.miao.edu.user.api.UserRemoteService;
import com.miao.edu.user.dto.UserDTO;
import com.miao.edu.user.service.UserService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;

/**
 * @author niemiao
 */
@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserRemoteService userRemoteService;

    @Autowired
    private UserService userService;



    @PostMapping(path = "/login")
    public ResponseDTO<String> login(String phone, String password, String code) {

        // 判断手机号是否非法
        if (StringUtils.isEmpty(phone) || !PhoneUtil.isPhone(phone)) {
            return ResponseDTO.response(201,"非法的手机号");
        }
        // 判断密码或验证码是否为空
        if (StringUtils.isEmpty(password) && StringUtils.isEmpty(code)) {
            return ResponseDTO.response(202,"密码或验证码为空");
        }
        // 默认密码登录
        int loginType = 0;
        // 如果密码为空并且验证码不为空，那么将登录类型设置为验证码登录
        if (StringUtils.isEmpty(password) && StringUtils.isNotEmpty(code)) {
            loginType = 1;
        }

        // 判断手机是否注册过
        if (!userRemoteService.isRegister(phone)) {
            // 判断登录方式是不是密码登录，不允许密码登录
            if (loginType == 0) {
                return ResponseDTO.response(203,"该手机未注册，不允许密码登录");
            }
            // 如果是验证码登录或者微信登录，需要注册一个新的账户
            UserDTO dto = new UserDTO();
            dto.setAccountNonExpired(true);
            dto.setAccountNonLocked(true);
            dto.setCredentialsNonExpired(true);
            dto.setStatus("ENABLE");
            dto.setRegIp(UserManager.getUserIP());
            dto.setName(phone);
            dto.setPassword(phone);
            dto.setCreateTime(new Date());
            dto.setIsDel(false);
            dto.setPhone(phone);
            dto.setUpdateTime(new Date());
            dto.setPortrait(null);
            // 保存用户信息（注册一个新的账号）
            UserDTO newUser = this.userRemoteService.saveUser(dto);

        }

        // 判断登录方式后，进行登录逻辑，获取token
        return userService.createAuthToken(phone, password, code, loginType);

    }

}
